import { useKeyPress } from "ahooks";
import { useDispatch } from "react-redux";
import {
  copyComponent,
  deleteComponent,
  pasteComponent,
  selectNextComponent,
  selectPreviousComponent,
} from "../store/componentsReducer";
import { ActionCreators } from "redux-undo";

//判断光标元素是否合法,可操作
const isActiveElementValid = () => {
  const activeElem = document.activeElement;
  //无dnd-kit
  // if (activeElem === document.body) return true;
  //dnk-kit
  if (activeElem === document.body) return true;
  if (activeElem?.matches('div[role="button"]')) return true;
  return false;
};

const useBindCanvasKey = () => {
  const dispatch = useDispatch();
  //删除
  useKeyPress(["backspace", "delete"], () => {
    if (!isActiveElementValid()) return;
    dispatch(deleteComponent());
  });
  //复制
  useKeyPress(["ctrl.c", "meta.c"], () => {
    if (!isActiveElementValid()) return;
    dispatch(copyComponent());
  });
  //粘贴
  useKeyPress(["ctrl.v", "meta.v"], () => {
    if (!isActiveElementValid()) return;
    dispatch(pasteComponent());
  });
  //选中上一个
  useKeyPress(["uparrow"], () => {
    if (!isActiveElementValid()) return;
    dispatch(selectPreviousComponent());
  });
  //选中下一个
  useKeyPress(["downarrow"], () => {
    if (!isActiveElementValid()) return;
    dispatch(selectNextComponent());
  });
  //撤销
  useKeyPress(["ctrl.z",'meta.z'], () => {
    if (!isActiveElementValid()) return;
    dispatch(ActionCreators.undo());
  }, {
    //严格匹配
    exactMatch:true
  });
  //重做
  useKeyPress(["ctrl.shift.z",'meta.shift.z'], () => {
    if (!isActiveElementValid()) return;
    dispatch(ActionCreators.redo());
  });
};

export default useBindCanvasKey;
